import request from "../../../utils/request"

Page({
  data: {
    reasons: [{
        id: 1,
        text: "不需要此项服务了"
      },
      {
        id: 2,
        text: "费用有点贵"
      },
      {
        id: 3,
        text: "临时有事，不方便服务"
      },
      {
        id: 4,
        text: "信息填写错误"
      },
      {
        id: 5,
        text: "重新下单"
      }
    ],
    selectedId: null,
    selectedText: '',
    orderNo: '', 
    fromType: '' // 标记跳转来源（cancel=取消订单，refund=退款）
  },

  selectReason(e) {
    const id = e.currentTarget.dataset.id;
    if (this.data.selectedId === id) {
      this.setData({
        selectedId: null,
        selectedText: ''
      });
      return;
    }
    const selectedText = this.data.reasons.find(item => item.id === id).text;
    this.setData({
      selectedId: id,
      selectedText: selectedText
    });
  },

  /**
   * 提交（重要修改：区分退款和取消订单）
   */
  submit() {
    if (!this.data.selectedId) {
      wx.showToast({
        title: '请选择原因',
        icon: 'none'
      });
      return;
    }

    // ✅ 根据来源区分调用不同的接口
    if (this.data.fromType === 'refund') {
      // ✅ 退款：调用退款接口
      this.handleRefund();
    } else {
      // ✅ 取消订单：调用更新订单接口
      this.handleCancel();
    }
  },

  /**
   * 处理退款（新增方法）
   */
  handleRefund() {
    const { orderNo, selectedText } = this.data;
    wx.showLoading({ title: '退款中...' });

    // 1. 先查询订单详情（获取订单ID、金额等信息）
    request({
      url: `/orderManagement/orderManagement/getOrderByOrderNO`,
      method: 'GET',
      data: { orderNo }
    }).then(resp => {
      console.log('查询订单返回：', resp);
      
      if (resp.data.code !== 200 || !resp.data.data) {
        throw new Error(resp.data.msg || '获取订单信息失败');
      }

      const order = resp.data.data;
      const userInfo = wx.getStorageSync('loginUserInfo'); // 获取当前登录用户

      if (!userInfo || !userInfo.userId) {
        throw new Error('未获取到用户信息，请重新登录');
      }

      // 2. 调用退款接口（✅ 关键修改！）
      return request({
        url: '/refund/refund',  // ✅ 正确的退款接口
        method: 'POST',
        data: {
          orderId: order.id,                          // 订单ID
          orderNo: orderNo,                           // 订单编号
          refundNo: this.generateRefundNo(),          // 退款编号（自动生成）
          refundAmount: order.orderAmount,            // 退款金额
          applicant: userInfo.userId,                 // 申请人ID
          applicationTime: this.formatDateTime(new Date()), // 申请时间
          refundTime: this.formatDateTime(new Date()),      // 退款时间
          refundStatus: 0,                            // 退款状态：0-退款成功
          refundReason: selectedText                  // 退款原因
        }
      });
    }).then(resp => {
      wx.hideLoading();
      console.log('退款接口返回：', resp);

      if (resp.data.code === 200) {
        wx.showToast({
          title: '退款成功',
          icon: 'success',
          duration: 2000
        });

        // 延迟返回并刷新订单列表
        setTimeout(() => {
          wx.navigateBack({
            delta: 1,
            success: () => {
              const pages = getCurrentPages();
              const prevPage = pages[pages.length - 2];
              if (prevPage && prevPage.getOrderList) {
                prevPage.getOrderList();
              }
            }
          });
        }, 1500);
      } else {
        wx.showToast({
          title: resp.data.msg || '退款失败',
          icon: 'none',
          duration: 2000
        });
      }
    }).catch(err => {
      wx.hideLoading();
      console.error('退款失败：', err);
      wx.showToast({
        title: err.message || '退款失败，请重试',
        icon: 'none',
        duration: 2000
      });
    });
  },

  /**
   * 处理取消订单（原有逻辑）
   */
  handleCancel() {
    const { orderNo, selectedText } = this.data;
    wx.showLoading({ title: '取消中...' });

    // 调用更新订单接口
    request({
      url: `/orderManagement/orderManagement`,
      method: 'PUT',
      data: {
        orderNo: orderNo,
        orderStatus: 5,              // 已关闭
        transactionStatus: 2,        // 交易关闭
        cancelReason: selectedText
      }
    }).then(resp => {
      wx.hideLoading();
      console.log('取消订单接口返回：', resp);

      if (resp.data.code === 200) {
        wx.showToast({
          title: '取消成功',
          icon: 'success',
          duration: 2000
        });

        // 延迟返回并刷新订单列表
        setTimeout(() => {
          wx.navigateBack({
            delta: 1,
            success: () => {
              const pages = getCurrentPages();
              const prevPage = pages[pages.length - 2];
              if (prevPage && prevPage.getOrderList) {
                prevPage.getOrderList();
              }
            }
          });
        }, 1500);
      } else {
        wx.showToast({
          title: resp.data.msg || '取消失败',
          icon: 'none',
          duration: 2000
        });
      }
    }).catch(err => {
      wx.hideLoading();
      console.error('取消订单失败：', err);
      wx.showToast({
        title: '取消失败，请重试',
        icon: 'none',
        duration: 2000
      });
    });
  },

  /**
   * 生成退款编号
   * 格式：TK + 年月日 + 8位随机数
   * 例如：TK20251027XXXXXXXX
   */
  generateRefundNo() {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hour = String(now.getHours()).padStart(2, '0');
    const minute = String(now.getMinutes()).padStart(2, '0');
    const second = String(now.getSeconds()).padStart(2, '0');
    const random = Math.floor(Math.random() * 100).toString().padStart(2, '0');
    
    return `TK${year}${month}${day}${hour}${minute}${second}${random}`;
  },

  /**
   * 格式化日期时间
   * @param {Date} date 
   * @returns {String} 格式：yyyy-MM-dd HH:mm:ss
   */
  formatDateTime(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hour = String(date.getHours()).padStart(2, '0');
    const minute = String(date.getMinutes()).padStart(2, '0');
    const second = String(date.getSeconds()).padStart(2, '0');
    
    return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const orderNo = options.orderNo;
    const fromType = options.fromType || 'cancel'; // 默认是取消订单
    
    console.log('页面加载参数：', { orderNo, fromType });
    
    this.setData({
      orderNo: orderNo,
      fromType: fromType
    });
  },
  
  back() {
    wx.navigateBack()
  },

  onReady() {},
  onShow() {},
  onHide() {},
  onUnload() {},
  onPullDownRefresh() {},
  onReachBottom() {},
  onShareAppMessage() {}
})

